def RandomString():
  import random
  import string
  chars = []
  for _ in xrange(64):
    chars.append(random.choice(string.printable))
  return ''.join(chars)


def XSRFKey():
  from pylib import models
  return models.Setting.Get('xsrf_key', RandomString)


def XSRFTokenForValue(value):
  import hashlib
  import hmac
  return hmac.new(XSRFKey(), value, hashlib.sha512).hexdigest()


def XSRFToken(request, response):
  """Return the preferred XSRF token."""
  return XSRFTokens(request, response).next()


def XSRFTokens(request, response):
  """Return all possible XSRF tokens."""
  from google.appengine.api import users
  user = users.get_current_user()
  if user:
    yield XSRFTokenForValue(user.email())

  import base64
  cookie = request.cookies.get('xsrf-msg')
  if cookie:
    cookie = base64.b64decode(cookie)
  else:
    import urlparse
    cookie = RandomString()
    response.headers.add_header(
        'Set-Cookie',
        'xsrf-msg=%s; domain=.%s; path=/' % (
            base64.b64encode(cookie),
            urlparse.urlparse(request.url).hostname))
  yield XSRFTokenForValue(cookie)
